package com.winit.openapi.wop.inbound.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.utils.Collections3;
import com.winit.openapi.constants.EnumConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.tms.controller.LogisticsPlanController;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;
import com.winit.pms.spi.winit.WinitProductItemService;
import com.winit.pms.spi.winit.WinitProductService;
import com.winit.pms.spi.winit.WinitRuleService;
import com.winit.pms.spi.winit.command.WinitProductQueryCommand;
import com.winit.pms.spi.winit.vo.WinitProduct;
import com.winit.tms.spi.common.TMSConstants;
import com.winit.tms.spi.logistics.LogisticsPlanService;
import com.winit.tms.spi.logistics.command.LogisticsPlanQueryCommand;
import com.winit.tms.spi.logistics.vo.LogisticsPlanVo;
import com.winit.ups.spi.command.CodeCommand;
import com.winit.ups.spi.warehouse.WarehouseService;
import com.winit.ups.spi.warehouse.vo.WarehouseVo;

@Controller
@RequestMapping(value = "winit/tms")
public class WHInboundLogisticsController extends BaseController {

    private static final Logger     logger = LoggerFactory.getLogger(LogisticsPlanController.class);

    @Resource
    private LogisticsPlanService    logisticsPlanService;

    @Resource
    private WinitRuleService        winitRuleService;

    @Resource
    private WinitProductService     winitProductService;

    @Resource
    private WinitProductItemService winitProductItemService;

    @Resource
    private WarehouseService        upsWarehouseService;
    
    /**
     * 查询物流计划
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/getLogisticsPlan")
    public String queryLogisticsPlan(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;

            ValidateUtil.validNotNull(json, "winitProductCode");
            ValidateUtil.validNotNull(json, "inspectionWarehouseCode");
            ValidateUtil.validNotNull(json, "destinationWarehouseCode");
            ValidateUtil.validMaxLength(json, "winitProductCode", 50, true);
            ValidateUtil.validMaxLength(json, "inspectionWarehouseCode", 50, true);
            ValidateUtil.validMaxLength(json, "destinationWarehouseCode", 50, true);

            String winitProductCode = json.getString("winitProductCode");
            WinitProductQueryCommand productCommand = new WinitProductQueryCommand();
            productCommand.setCode(winitProductCode);
            WinitProduct product = winitProductService.queryProduct(productCommand);
            if (null == product) {
                throw new ApiException(ErrorCode.WINIT_PRODUCT_NOT_EXISTS, winitProductCode);
            }

            if (json.containsKey("destinationWarehouseCode")) {
                CodeCommand warehouseCommand = new CodeCommand();
                warehouseCommand.setCode(json.getString("destinationWarehouseCode"));
                WarehouseVo warehouse = upsWarehouseService.queryWarehouseByCode(warehouseCommand);
                if (null == warehouse) {
                    throw new ApiException(ErrorCode.WAREHOUSE_CODE_NOT_EXISTS,
                        json.getString("destinationWarehouseCode"));
                }
            }
            if (json.containsKey("inspectionWarehouseCode")) {
                CodeCommand warehouseCommand = new CodeCommand();
                warehouseCommand.setCode(json.getString("inspectionWarehouseCode"));
                WarehouseVo warehouse = upsWarehouseService.queryWarehouseByCode(warehouseCommand);
                if (null == warehouse) {
                    throw new ApiException(ErrorCode.WAREHOUSE_CODE_NOT_EXISTS,
                        json.getString("inspectionWarehouseCode"));
                }
            }

            String productCode = json.getString("winitProductCode");
            WinitProductQueryCommand suCommand = new WinitProductQueryCommand();
            suCommand.setCode(productCode);
            String delivery = "";
            String planType = TMSConstants.KUAIDI_TYPE;
            try {
                List<WinitProduct> serviceList = winitProductItemService.queryServiceItemAllByProductIdOrCode(suCommand);
                // 找出服务里的运输方式 空运:C0301|C030102 海运:C0302|C030202 快递:C0303
                if (Collections3.isNotEmpty(serviceList)) {
                    for (WinitProduct serviceUnit : serviceList) {
                        if (EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_AIR.getCode()
                            .equals(serviceUnit.getServiceCatalogCode())
                            || EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_AIR_V2.getCode()
                                .equals(serviceUnit.getServiceCatalogCode())) {
                            planType = TMSConstants.KONGYUN_TYPE;
                            break;
                        } else if (EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_SEA.getCode()
                            .equals(serviceUnit.getServiceCatalogCode())
                                   || EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_SEA_V2.getCode()
                                       .equals(serviceUnit.getServiceCatalogCode())) {
                            planType = TMSConstants.HAIYUN_TYPE;
                            break;
                        } else if (EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_EXPRESS.getCode()
                            .equals(serviceUnit.getServiceCatalogCode())) {
                            planType = TMSConstants.KUAIDI_TYPE;
                            break;
                        }
                    }
                }
                WinitProductQueryCommand querycommand = new WinitProductQueryCommand();
                querycommand.setCode(productCode);
                WinitProduct winitProduct = winitProductService.queryProduct(querycommand);
                delivery = winitProduct.getAssemblyType();
            } catch (Exception e) {
                logger.error("查询服务分类失败", e);
            }

            String inspectionWarehouseCode = json.getString("inspectionWarehouseCode");
            String purposeWarehouseCode = json.getString("destinationWarehouseCode");

            LogisticsPlanQueryCommand command = new LogisticsPlanQueryCommand();
            command.setDelivery(delivery);
            command.setPlanType(planType);
            command.setInspectionWarehouseCode(inspectionWarehouseCode);
            command.setPurposeWarehouseCode(purposeWarehouseCode);
            List<LogisticsPlanVo> planVos = logisticsPlanService.queryLogisticsPlan(command);
            List<Map<String, String>> planList = new ArrayList<Map<String, String>>();
            if (CollectionUtils.isNotEmpty(planVos)) {
                for (LogisticsPlanVo logisticsPlanVo : planVos) {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("planCode", String.valueOf(logisticsPlanVo.getId()));
                    map.put("planName", logisticsPlanVo.getPlanName());
                    map.put("planType", logisticsPlanVo.getPlanType());
                    map.put("createOrderDeadline",
                        DateUtil.parse2String(logisticsPlanVo.getEndPlaceorderDate(), DateUtil.FULL_DATE_STRING));
                    map.put("pickupPackageDeadline",
                        DateUtil.parse2String(logisticsPlanVo.getEndDeliveryDate(), DateUtil.FULL_DATE_STRING));
                    map.put("planOutboudDate",
                        DateUtil.parse2String(logisticsPlanVo.getExpectedOutboudDate(), DateUtil.FULL_DATE_STRING));
                    map.put("planShelfDate",
                        DateUtil.parse2String(logisticsPlanVo.getExpectedWarehouseDate(), DateUtil.FULL_DATE_STRING));
                    map.put("createOrderDeadline",
                        DateUtil.parse2String(logisticsPlanVo.getEndPlaceorderDate(), DateUtil.FULL_DATE_STRING));

                    planList.add(map);
                }
            }
            Map<Object, Object> data = new HashMap<Object, Object>();
            data.put("planList", planList);
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
}
